<?php
class Util {
	static function dt_doctrine2ar($dataRecebida) {
		$dt = array();
		$parts = explode(' ',$dataRecebida);
		$data = $parts[0];
		$hora = $parts[1];
		$dt_parts = explode('-',$data);
		$dt['ano'] = $dt_parts[0];
		$dt['mes'] = $dt_parts[1];
		$dt['dia'] = $dt_parts[2];
		$hr_parts = explode(':',$hora);
		$dt['hora'] = $hr_parts[0];
		$dt['minuto'] = $hr_parts[1];
		$dt['segundo'] =
		isset($hr_parts[2])
		? $hr_parts[2]
		: '00';
		return $dt;
	}

	static function dt_doctrine2time($dataRecebida) {
		$dt = self::dt_doctrine2ar($dataRecebida);
		return mktime(
		$dt['hora'],
		$dt['minuto'],
		$dt['segundo'],
		$dt['mes'],
		$dt['dia'],
		$dt['ano']
		);
	}

	/**
	 * @param string|int $Year
	 * Displays <a href="http://br.php.net/easter_date">php.net</a>
	 * @link http://br.php.net/easter_date
	 */
	public static function retornarPascoa($Year)
	{
		/*
		G is the Golden Number-1
		H is 23-Epact (modulo 30)
		I is the number of days from 21 March to the Paschal full moon
		J is the weekday for the Paschal full moon (0=Sunday,
		1=Monday, etc.)
		L is the number of days from 21 March to the Sunday on or before
		the Paschal full moon (a number between -6 and 28)
		*/

		$G = $Year % 19;
		$C = (int)($Year / 100);
		$H = (int)($C - (int)($C / 4) - (int)((8*$C+13) / 25) + 19*$G + 15) % 30;
		$I = (int)$H - (int)($H / 28)*(1 - (int)($H / 28)*(int)(29 / ($H + 1))*((int)(21 - $G) / 11));
		$J = ($Year + (int)($Year/4) + $I + 2 - $C + (int)($C/4)) % 7;
		$L = $I - $J;
		$m = 3 + (int)(($L + 40) / 44);
		$d = $L + 28 - 31 * ((int)($m / 4));
		$y = $Year;
		$E = mktime(0,0,0, $m, $d, $y);

		return $E;
	}

	/**
	* @author Rodrigo R�gis Palmeira <regisbsb@gmail.com>
	* @param string $ano - ano em que se quer calcular os feriados
	* @return array com feriados nacionais do ano informado do ano (fixo e moveis)
	*/
	public static function retornarFeriados($ano)
	{
		$dia = 86400;
		$datas = array();
		$datas['pascoa'] = self::retornarPascoa($ano);
		$datas['sexta_santa'] = $datas['pascoa'] - (2 * $dia);
		$datas['carnaval'] = $datas['pascoa'] - (47 * $dia);
		$datas['corpus_cristi'] = $datas['pascoa'] + (60 * $dia);

		$feriados = array (
			'Ano Novo'						=> '01/01/'.date('Y'),
			'Carnaval'						=> date('d/m/Y',$datas['carnaval']),
			'Sexta-Feira Santa'				=> date('d/m/Y',$datas['sexta_santa']),
			'P�scoa'						=> date('d/m/Y',$datas['pascoa']),
			'Tiradentes'					=> '21/04/'.date('Y'),
			'Dia do Trabalhador'			=> '01/05/'.date('Y'),
			'Corpus Cristi'					=> date('d/m/Y',$datas['corpus_cristi']),
			'Dia da Independ�ncia'			=> '07/09/'.date('Y'),
			'Nossa Senhora de Aparecida'	=> '12/10/'.date('Y'),
			'Dia de Finados'				=> '02/11/'.date('Y'),
			'Proclama��o da Rep�blica'		=> '15/11/'.date('Y'),
			'Natal'							=>	'25/12/'.date('Y')
		);
		return $feriados;
	}

	/**
	 * @author Rodrigo R�gis Palmeira <regisbsb@gmail.com>
	 * @param int $soma - dias a serem somados
	 * @param bolean $uteis - considera dias uteis - default false
	 * @param date $data - data inicial v�lida - default date('d/m/Y')
	 * @param string $format - formato de data a ser retornado
	 * @return string - data em formado d/m/Y
	 */
	public static function somarData($soma, $uteis = false, $data = null, $format = 'd/m/Y')
	{
		$ar = explode("/",$data);
		if (!empty($ar[0]) && !empty($ar[1]) && !empty($ar[2]))
		{
			if (checkdate($ar[1],$ar[0],$ar[2]))
			{
				$dia = $ar[0];
				$mes = $ar[1];
				$ano = $ar[2];
			}
			else
			{
				return "Informe uma data v�lida!";
			}
		}
		else
		{
			$dia = date('d');
			$mes = date('m');
			$ano = date('Y');
		}

		if ($uteis)
		{
			$contDia = 0;
			$qtdDiasUteis = 0;

			while ($qtdDiasUteis < $soma)
			{
				$contDia++;

				if (($dias_da_semana = gmdate('w', strtotime('+'.$contDia.' day', mktime(0, 0, 0, $mes, $dia, $ano))) ) != '0' &&
					 $dias_da_semana != '6'  &&
					 (!in_array(date('d/m/Y', mktime(0, 0, 0, $mes, $dia + $contDia, $ano)),self::retornarFeriados($ano))))
				{
					$qtdDiasUteis++;
				}
			}
			$novaData = date($format, mktime(0, 0, 0, $mes, $dia + $contDia, $ano));
		}
		else
		{
			$novaData = date($format, mktime(0, 0, 0, $mes, $dia + $soma, $ano));
		}

		return $novaData;
	}

  public static function comparaDatas( $data1, $data2,$comparacao = '>=' ) {
    $i_ar = explode("/",$data1);
    $f_ar = explode("/",$data2);

    $i_dia = $i_ar[0];
    $i_mes = $i_ar[1];
    $i_ano = $i_ar[2];

    $f_dia = $f_ar[0];
    $f_mes = $f_ar[1];
    $f_ano = $f_ar[2];

    $dt1 = mktime(0, 0, 0, $i_mes, $i_dia, $i_ano); //timestamp
    $dt2 = mktime(0, 0, 0, $f_mes, $f_dia, $f_ano); //timestamp

    if (($comparacao == '>=' && $dt1 >= $dt2) || ($comparacao == '>' && $dt1 > $dt2 ) || ($comparacao == '==' && $dt1 == $dt2 ))
    {
      return true;
    }
    else
    {
      return false;
    }
  }

  public static function difencaDeDiasEntreDatas( $data1, $data2, $uteis = false) {
    $i_ar = explode("/",$data1);
    $f_ar = explode("/",$data2);

    $i_dia = $i_ar[0];
    $i_mes = $i_ar[1];
    $i_ano = $i_ar[2];

    $f_dia = $f_ar[0];
    $f_mes = $f_ar[1];
    $f_ano = $f_ar[2];

    $dt1 = mktime(0, 0, 0, $i_mes, $i_dia, $i_ano); //timestamp
    $dt2 = mktime(0, 0, 0, $f_mes, $f_dia, $f_ano); //timestamp

    if ( $dt1 <= $dt2 ) {  $dif = $dt2 - $dt1; }else {   $dif = $dt1 - $dt2; }

    $soma = ($dif/60/60/24);

    if($uteis){ 	$soma	= self::retornaDiasUteis($soma, $data1);   }

    return $soma;
  }

  public static function retornaDiasUteis($dias, $data)
  {
    $ar = explode("/",$data);
    if (checkdate($ar[1],$ar[0],$ar[2]))
    {
      $dia = $ar[0];
      $mes = $ar[1];
      $ano = $ar[2];
    }

    $contDia = 0;
    $qtdDiasUteis = 0;

    while ($contDia <= $dias)
    {
      $dias_da_semana = gmdate('w', strtotime('+'.$contDia.' day', mktime(0, 0, 0, $mes, $dia, $ano)));

      if ( ($dias_da_semana != 0) && ($dias_da_semana != 6) &&
           (!in_array(date('d/m/Y', mktime(0, 0, 0, $mes, ($dia+$contDia), $ano)), self::retornarFeriados($ano)))
          )
      {
        $qtdDiasUteis++;
      }
      $contDia++;
    }
    return $qtdDiasUteis;
  }

	/**
	 * Retorna as unidades do usu�rio de acordo com as credentials
	 *
	 * @author Rodrigo R�gis Palmeira
	 * @param array $credentials - default = credentials do usu�rio logado
	 * @return array unidade(s) que o usu�rio pertence ou null para todos os acessos
	 */
	public static function retornarUnidadePorCredential($credentials = array(), $string = true)
	{
		if (empty($credentials))
			$credentials = $_SESSION['symfony/user/sfUser/credentials'];

		$tp_unidade = array();
		if ($string)
		{
			foreach($credentials as $credential)
			{
				switch ($credential)
				{
					case 'integra_ope_divap_tecnico':
					case 'integra_ope_divap_coord':
					case 'integra_ope_divap_chefe':
						$tp_unidade[] = "'V'";
						break;
					case 'integra_ope_dicin_tecnico':
					case 'integra_ope_dicin_coord':
					case 'integra_ope_dicin_chefe':
						$tp_unidade[] = "'C'";
						break;
					case 'integra_ope_diata':
						$tp_unidade[] = "'T'";
						break;
					case 'integra_ope_coori':
						$tp_unidade[] = "'C'";
						$tp_unidade[] = "'V'";
						break;
					case 'integra_dem_mant_gabin':
					case 'integra_dem_respondedor_gabin':
						$tp_unidade[] = "'G'";
						break;
					case 'integra_dem_mant_profe ':
					case 'integra_dem_respondedor_profe':
						$tp_unidade[] = "'P'";
						break;
				}
			}
		}
		else
		{
					foreach($credentials as $credential)
			{
				switch ($credential)
				{
					case 'integra_ope_divap_tecnico':
					case 'integra_ope_divap_coord':
					case 'integra_ope_divap_chefe':
						$tp_unidade[] = "V";
						break;
					case 'integra_ope_dicin_tecnico':
					case 'integra_ope_dicin_coord':
					case 'integra_ope_dicin_chefe':
						$tp_unidade[] = "C";
						break;
					case 'integra_ope_diata':
						$tp_unidade[] = "T";
						break;
					case 'integra_ope_coori':
						$tp_unidade[] = "C";
						$tp_unidade[] = "V";
						break;
					case 'integra_dem_mant_gabin':
					case 'integra_dem_respondedor_gabin':
						$tp_unidade[] = "G";
						break;
					case 'integra_dem_mant_profe ':
					case 'integra_dem_respondedor_profe':
						$tp_unidade[] = "P";
						break;
				}
			}
		}
		return array_unique($tp_unidade);
	}

	public static function contemCeV($tp_unidade = array())
	{
		$contador = 0;
		$retorno = false;
		foreach ($tp_unidade as $unidade)
		{
			if($unidade == "'C'" ||$unidade == "'V'" )
				$contador ++;
		}
		if($contador > 1)
			$retorno = true;
		return $retorno;
	}

	public static function formatarCPF_CNPJ($campo, $formatado = true)
	{
		//retira formato
		$codigoLimpo = str_replace(array('[',"'",'-','.','/'), '', $campo);// ereg_replace("[' '-./ t]",'',$campo);
		// pega o tamanho da string menos os digitos verificadores
		$tamanho = (strlen($codigoLimpo) -2);
		//verifica se o tamanho do c�digo informado � v�lido
		if ($tamanho != 9 && $tamanho != 12){
			return false;
		}

		if ($formatado){
			// seleciona a m�scara para cpf ou cnpj
			$mascara = ($tamanho == 9) ? '###.###.###-##' : '##.###.###/####-##';

			$indice = -1;
			for ($i=0; $i < strlen($mascara); $i++) {
				if ($mascara[$i]=='#') $mascara[$i] = $codigoLimpo[++$indice];
			}
			//retorna o campo formatado
			$retorno = $mascara;

		}else{
			//se n�o quer formatado, retorna o campo limpo
			$retorno = $codigoLimpo;
		}

		return $retorno;
	}

  public static function validaCPF($value)
  {
    //Retira os formatos
    $strCPF = preg_replace('/[^0-9]/', '', $value);
    //Verifica o tamanho
    if (strlen($strCPF)<>11) {
      return false;
    } else {

      //Verifica se todos digitos sao iguais. Ex: 11111111111
      for ($i = 0; $i < 10; $i++){
        if ($strCPF == str_pad('', 11, $i)){
          return false;
        }
      }

      //Verifica primeiro digito verificador
      $intSoma = 0;
      for ($i = 1; $i < strlen($strCPF) - 1; $i++) {
        $intSoma += ((int) $strCPF[$i - 1]) * (strlen($strCPF) - $i);
      }

      $intDv = 11 - ($intSoma % 11);
      if ($intDv >= 10) {
        $intDv = 0;
      }
      if ($intDv <> ((int) $strCPF[strlen($strCPF) - 2])) {
        return false;
      } else {

        //Verifica segundo digito verificador
        $intSoma = 0;
        for ($i = 1; $i < strlen($strCPF); $i++) {
          $intSoma += ((int) $strCPF[$i - 1]) * (strlen($strCPF) - $i + 1);
        }
        $intDv = 11 - ($intSoma % 11);
        if ($intDv >= 10) {
          $intDv = 0;
        }
        return  $intDv == ((int) $strCPF[strlen($strCPF) - 1]);
      }
    }
  }

	/**
	 * @author Rodrigo R�gis Palmeira
	 * @link http://www.rodrigoregis.com.br
	 * @param string $html
	 * @return file.xls
	 */
	public static function htmltoXLS($html, $nome='file.xls')
	{
		header ("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
		header ("Cache-Control: no-cache, must-revalidate");
		header ("Pragma: no-cache");
		header ("Content-type: application/vnd.ms-excel");
		header ("Content-Disposition: attachment; filename=\"{$nome}\"" );
		header ("Content-Description: PHP Generated Data" );

		echo $html;
		exit();
	}

  /**
    * @author Rodrigo R�gis Palmeira
    * @link http://www.rodrigoregis.com.br
    * @param string $html
    * @return file.doc
    */
  public static function toDOC($html, $nome = 'file.doc', $destino = null)
  {
  	if (!$destino)
  	{
  		header("Content-type: application/vnd.ms-word");
  		header("Content-type: application/force-download");
  		header("Content-Disposition: attachment; filename=\"{$nome}\"");
  		header("Pragma: no-cache");
  		echo $html;
  		//exit();
  	}
  	else
  	{
  		file_put_contents($destino.'/'.$nome, $html);
  		//exit();
  	}
  }

	/**
	 * @author Leonardo C Magalh�es
	 * @param Formata Processo
	 * @return
	 */
	public static function formataProcesso($nuProcesso)
	{
		$nuProc = (substr($nuProcesso, 0, 5).'.'.substr($nuProcesso, 5, 6).'/'.substr($nuProcesso,11, 4).'-'.substr($nuProcesso,15, 2));
		return  $nuProc;
	}

	public static function limpaDocumenta($nuDocumenta)
	{
		if (strpos($nuDocumenta,'/'))
		{
  			$nuTramitaTemp  = explode('/', $nuDocumenta);
			$nuTramitaTemp2 = explode('-', $nuTramitaTemp[1]);
			$nuDocumenta = $nuTramitaTemp2[0].$nuTramitaTemp[0];
		}
		return $nuDocumenta;
	}

	public static function removerCaracter($string){
	    $string = ereg_replace("[����]","a",$string);
	    $string = ereg_replace("[����]","A",$string);
	    $string = ereg_replace("[���]","e",$string);
	    $string = ereg_replace("[���]","E",$string);
	    $string = ereg_replace("[��]","i",$string);
	    $string = ereg_replace("[��]","I",$string);
	    $string = ereg_replace("[�����]","o",$string);
	    $string = ereg_replace("[����]","O",$string);
	    $string = ereg_replace("[���]","u",$string);
	    $string = ereg_replace("[���]","U",$string);
	    $string = ereg_replace("�","c",$string);
	    $string = ereg_replace("�","C",$string);
	    $string = ereg_replace("[][><}{)(:;,!?*%~^`&#@-]","",$string);
	    $string = ereg_replace(" ","_",$string);

	    return $string;
	}

	/**
	 * Retorna a unidade do usu�rio de acordo com a credential
	 *
	 * @author Andrey C. Moretti
	 * @param array $credentials - default = credentials do usu�rio logado
	 * @return array unidade(s) que o usu�rio pertence ou null para todos os acessos
	 */
	public static function retornarOrgaoOperacionalCredential($credentials = array())
	{
		if (empty($credentials))
			$credentials = $_SESSION['symfony/user/sfUser/credentials'];

		//Unidades
		$array_unidade = array("dicin", "divap", "coori", "audit", "profe", "diata");

		$array_orgao = array();

		foreach($credentials as $c)
		{
			foreach($array_unidade as $au)
			{
				if(strpos($c, "ope_".$au) !== false || $c == 'integra_administrador')
				{
					$orgao 									= SOrgaoTable::lerUnidadePorArSigla(strtoupper($au));
					$array_orgao[$orgao[0]->nu_seq_orgao]	= strtoupper($au);
				}
			}
		}

		return $array_orgao;
	}

	/**
	 * Fun��o para formatar qualquer mascara.
	 * A mascara deve ser informada com # Ex: ##/##/####
	 * @param string $string
	 * @param string $format
	 */
	public static function formatAll($string, $mascara)
	{
	    if($string)
	    {
    	    $stringLimpa = str_replace("[][><}{)(:;,!?*%&#@-/\]", "", $string);

    	    $indice = -1;
    		for ($i=0; $i < strlen($mascara); $i++) {
    			if ($mascara[$i] == '#')
    			    $mascara[$i] = $stringLimpa[++$indice];
    		}

    		//retorna a string formatada
    		return $mascara;
	    }
	}

/**
 * A PHP implementation of RC4 based on the original C code from
 * the 1994 usenet post:
 *
 * http://groups.google.com/groups?selm=sternCvKL4B.Hyy@netcom.com
 *
 * You may distribute under any terms and any license of your
 * choosing providing you credit the author for his work.
 *
 * @author    Michael Cutler <m@cotdp.com>
 * @copyright (c) 2006 Michael Cutler
 * @version   1.0
 */


   /**
    * An optimised, self-contained RC4 implementation in PHP
    *
    * @param  key_str   the key as a binary string
    * @param  data_str  the data to decrypt/encrypt as a binary string
    * @return           the result of the RC4 as a binary string
    */
   public static function rc4($key_str, $data_str)
   {
      // convert input string(s) to array(s)
      $key = array();
      $data = array();
      for ( $i = 0; $i < strlen($key_str); $i++ ) {
         $key[] = ord($key_str{$i});
      }
      for ( $i = 0; $i < strlen($data_str); $i++ ) {
         $data[] = ord($data_str{$i});
      }
      // prepare key
      $state = array( 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255 );
      // removed the following two lines as the array() version above is *significantly* faster [23% on PHP 4.3.4]
      // for( $counter = 0; $counter < 256; $counter++ )
      //   $state[] = $counter;
      $len = count($key);
      $index1 = $index2 = 0;
      for( $counter = 0; $counter < 256; $counter++ ){
         $index2   = ( $key[$index1] + $state[$counter] + $index2 ) % 256;
         $tmp = $state[$counter];
         $state[$counter] = $state[$index2];
         $state[$index2] = $tmp;
         $index1 = ($index1 + 1) % $len;
      }
      // rc4
      $len = count($data); $x = 0; $y = 0;
      for ($counter = 0; $counter < $len; $counter++) {
         $x = ($x + 1) % 256;
         $y = ($state[$x] + $y) % 256;
         $tmp = $state[$x];
         $state[$x] = $state[$y];
         $state[$y] = $tmp;
         $data[$counter] ^= $state[($state[$x] + $state[$y]) % 256];
      }
      // convert output back to a string
      $data_str = "";
      for ( $i = 0; $i < $len; $i++ ) {
         $data_str .= chr($data[$i]);
      }
      return $data_str;
   }

   public static function carregaUrlExterna($url)
   {
		$session = curl_init($url);
		curl_setopt($session, CURLOPT_HEADER, false);
		curl_setopt ($session, CURLOPT_FOLLOWLOCATION, '1');
		curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
		$dados = curl_exec($session);
		curl_close($session);

		return $dados;
   }
   
	public static function gerarString($tamanho, $crip = null) {
        $conteudo = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $string = null;
        for($i=0;$i<$tamanho;$i++) {
            $string .= $conteudo{rand(0,35)};
        }
        
        if($crip)
        {
        	return array(
        		$string,
        		$crip($string)
        	);
        }
        return $string;
    }
    
    public static function getHtmlContent(sfActions $action, $layout = false)
	{
	    sfConfig::set('sf_web_debug', false);
	    $action->setLayout($layout);
	    $context = $action->getContext();
	    //clear http headers
	    $context->getResponse()->clearHttpHeaders();
	
	    /*get the view, execute n render with variables*/
	    $view = $context->getController()->getView($action->getModuleName(), $action->getActionName(), 'Success');
	    $view->execute();
	    $view->getAttributeHolder()->add($action->getVarHolder()->getAll());
	    $content = $view->render();
	    return $content;
	}
}
?>